// 问题相关功能

// 加载问题列表
window.loadQuestions = function(page = 1, searchKeyword = '') {
    currentPage = page;
    
    const url = `/knowledge-qa/api/question/list?page=${page}&size=10${searchKeyword ? `&keyword=${encodeURIComponent(searchKeyword)}` : ''}`;
    
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const questions = data.questions || [];
                const questionList = document.getElementById('questionList');
                
                if (questions.length === 0) {
                    questionList.innerHTML = '<p style="text-align:center; color:#999; padding:2rem;">暂无问题</p>';
                } else {
                    let html = '';
                    questions.forEach(question => {
                        html += `
                            <div class="question-item">
                                <div class="question-header">
                                    <h3 onclick="showQuestionDetail(${question.id})" class="question-title">${question.title}</h3>
                                    <div class="question-meta">
                                        <span class="question-user">${question.username}</span>
                                        <span class="question-time">${formatDate(question.createTime)}</span>
                                        <span class="question-status">${getStatusText(question.status)}</span>
                                    </div>
                                </div>
                                <div class="question-content">
                                    ${truncateText(question.content, 150)}
                                </div>
                                <div class="question-footer">
                                    <span class="question-reward">悬赏: ${question.rewardAmount}金币</span>
                                    <span class="question-view-count">浏览量: ${question.viewCount}</span>
                                    <span class="question-answer-count">回答量: ${question.answerCount}</span>
                                </div>
                            </div>
                        `;
                    });
                    questionList.innerHTML = html;
                }
                
                // 生成分页
                generatePagination(data.total, data.pageSize, data.currentPage);
            } else {
                document.getElementById('questionList').innerHTML = '<p style="text-align:center; color:#ff4d4f; padding:2rem;">加载失败</p>';
            }
        })
        .catch(error => {
            console.error('加载问题列表失败:', error);
            document.getElementById('questionList').innerHTML = '<p style="text-align:center; color:#ff4d4f; padding:2rem;">加载失败，请稍后重试</p>';
        });
};

// 搜索问题
window.searchQuestions = function() {
    const keyword = document.getElementById('searchInput').value;
    loadQuestions(1, keyword);
};

// 显示发布问题模态框
window.showPublishQuestionModal = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    publishQuestionModal.style.display = 'block';
};

// 关闭发布问题模态框
window.closePublishQuestionModal = function() {
    publishQuestionModal.style.display = 'none';
    // 清空表单
    document.getElementById('publishQuestionForm').reset();
    document.getElementById('publishQuestionMessage').style.display = 'none';
};

// 发布问题
window.publishQuestion = function() {
    const title = document.getElementById('questionTitle').value;
    const content = document.getElementById('questionContent').value;
    const reward = document.getElementById('questionReward').value;
    
    if (!title || !content || !reward) {
        showMessage('publishQuestionMessage', '请填写完整的问题信息', false);
        return;
    }
    
    if (isNaN(reward) || reward <= 0) {
        showMessage('publishQuestionMessage', '请输入有效的悬赏金额', false);
        return;
    }
    
    // 发送发布问题请求
    fetch('/knowledge-qa/api/question/publish', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({userId: currentUserId, title, content, rewardAmount: parseInt(reward)})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('publishQuestionMessage', '发布成功', true);
            
            // 5秒后关闭模态框并刷新问题列表
            setTimeout(() => {
                closePublishQuestionModal();
                showQuestionList();
            }, 1500);
        } else {
            showMessage('publishQuestionMessage', data.message || '发布失败', false);
        }
    })
    .catch(error => {
        console.error('发布问题失败:', error);
        showMessage('publishQuestionMessage', '发布失败，请稍后重试', false);
    });
}

// 显示问题详情模态框
window.showQuestionDetail = function(questionId) {
    // 创建问题详情模态框
    createQuestionDetailModal(questionId);
};

// 创建问题详情模态框
window.createQuestionDetailModal = function(questionId) {
    // 检查是否已存在问题详情模态框，如果有则移除
    const existingModal = document.getElementById('questionDetailModal');
    if (existingModal) {
        document.body.removeChild(existingModal);
    }
    
    // 创建新的模态框
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.style.display = 'block';
    modal.id = 'questionDetailModal';
    
    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.innerHTML = `
        <span class="close" onclick="closeQuestionDetailModal()">&times;</span>
        <div id="questionDetailContent" style="padding: 1rem 0;">
            <p style="text-align:center; color:#999;">加载中...</p>
        </div>
    `;
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
    
    // 加载问题详情
    loadQuestionDetail(questionId);
}

// 关闭问题详情模态框
window.closeQuestionDetailModal = function() {
    const modal = document.getElementById('questionDetailModal');
    if (modal) {
        modal.style.display = 'none';
    }
};

// 加载问题详情
window.loadQuestionDetail = function(questionId) {
    fetch(`/knowledge-qa/api/question/${questionId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.question) {
                const question = data.question;
                const contentDiv = document.getElementById('questionDetailContent');
                
                let html = `
                    <div class="question-detail">
                        <h2>${question.title}</h2>
                        <div class="question-meta">
                            <span class="question-user">${question.username}</span>
                            <span class="question-time">${formatDate(question.createTime)}</span>
                            <span class="question-status">${getStatusText(question.status)}</span>
                            <span class="question-reward">悬赏: ${question.rewardAmount}金币</span>
                        </div>
                        <div class="question-content">
                            ${question.content}
                        </div>
                `;
                
                // 如果是问题发布者，显示操作按钮
                if (window.currentUserId && parseInt(window.currentUserId) === question.userId) {
                    html += `
                        <div class="question-actions">
                            <button class="btn btn-primary" onclick="closeQuestion(${questionId})">关闭问题</button>
                            <button class="btn btn-danger" onclick="deleteQuestion(${questionId})">删除问题</button>
                        </div>
                    `;
                }
                
                html += `
                    </div>
                    <div class="answers-section">
                        <h3>回答量: ${question.answerCount}</h3>
                        <div id="answersList"></div>
                        <div class="answer-form">
                            <h4>我的回答</h4>
                            <textarea id="answerContent" rows="4" placeholder="请输入您的回答..."></textarea>
                            <button class="btn btn-primary" onclick="submitAnswer(${questionId})">提交回答</button>
                        </div>
                    </div>
                `;
                
                contentDiv.innerHTML = html;
                
                // 加载回答列表
                loadQuestionAnswers(questionId, question);
            } else {
                document.getElementById('questionDetailContent').innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载失败</p>';
            }
        })
        .catch(error => {
            console.error('加载问题详情失败:', error);
            document.getElementById('questionDetailContent').innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载失败，请稍后重试</p>';
        });
}

// 加载问题回答列表
function loadQuestionAnswers(questionId, question) {
    fetch(`/knowledge-qa/api/answer/question/${questionId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const answers = data.answers || [];
                const answersList = document.getElementById('answersList');
                
                if (answers.length === 0) {
                    answersList.innerHTML = '<p style="text-align:center; color:#999; padding:2rem;">暂无回答</p>';
                } else {
                    let html = '';
                    answers.forEach(answer => {
                        const isAccepted = answer.isAccepted || false; // 布尔值表示是否已采纳
                        
                        html += `
                            <div class="answer-item ${isAccepted ? 'accepted' : ''}">
                                <div class="answer-meta">
                                    <span class="answer-user">${answer.username || '未知用户'}</span>
                                    <span class="answer-time">${formatDate(answer.createTime)}</span>
                                    ${isAccepted ? '<span class="accepted-badge">已采纳</span>' : ''}
                                </div>
                                <div class="answer-content">
                                    ${answer.content}
                                </div>
                                <div class="answer-actions">
                        `;
                        
                        // 如果是问题发布者且回答未被采纳，显示采纳按钮
                        if (window.currentUserId && question && parseInt(window.currentUserId) === question.userId && !isAccepted) {
                            html += `
                                <button class="btn btn-primary" onclick="acceptAnswer(${answer.id}, ${questionId})">采纳答案</button>
                            `;
                        }
                        
                        html += `
                                </div>
                            </div>
                        `;
                    });
                    answersList.innerHTML = html;
                }
            } else {
                document.getElementById('answersList').innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载回答失败</p>';
            }
        })
        .catch(error => {
            console.error('加载回答失败:', error);
            document.getElementById('answersList').innerHTML = '<p style="text-align:center; color:#ff4d4f;">加载回答失败，请稍后重试</p>';
        });
}

// 提交回答
function submitAnswer(questionId) {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    
    const content = document.getElementById('answerContent').value;
    
    if (!content) {
        alert('请输入回答内容');
        return;
    }
    
    // 发送回答请求
    fetch('/knowledge-qa/api/answer/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({questionId, userId: currentUserId, content})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 清空回答框
            document.getElementById('answerContent').value = '';
            
            // 刷新回答列表
            loadQuestionAnswers(questionId);
        } else {
            alert(data.message || '提交回答失败');
        }
    })
    .catch(error => {
        console.error('提交回答失败:', error);
        alert('提交回答失败，请稍后重试');
    });
}

// 采纳答案
function acceptAnswer(answerId, questionId) {
    if (confirm('确定要采纳这个答案吗？采纳后将完成问题并转账悬赏金币')) {
        fetch('/knowledge-qa/api/question/accept-answer', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({questionId, answerId})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('采纳成功！悬赏金币已转账给回答者');
                // 刷新问题详情
                loadQuestionDetail(questionId);
            } else {
                alert(data.message || '采纳失败');
            }
        })
        .catch(error => {
            console.error('采纳答案失败:', error);
            alert('采纳答案失败，请稍后重试');
        });
    }
}

// 关闭问题
window.closeQuestion = function(questionId) {
    if (confirm('确定要关闭这个问题吗？关闭后将无法回答。')) {
        fetch(`/knowledge-qa/api/question/close/${questionId}`, {
            method: 'PUT'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('关闭成功');
                // 刷新问题列表
                showQuestionList();
                // 关闭详情模态框
                closeQuestionDetailModal();
            } else {
                alert(data.message || '关闭失败');
            }
        })
        .catch(error => {
            console.error('关闭问题失败:', error);
            alert('关闭问题失败，请稍后重试');
        });
    }
}

// 删除问题
window.deleteQuestion = function(questionId) {
    if (confirm('确定要删除这个问题吗？删除后将无法恢复。')) {
        fetch(`/knowledge-qa/api/question/${questionId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('删除成功');
                // 刷新问题列表
                showQuestionList();
                // 关闭详情模态框
                closeQuestionDetailModal();
            } else {
                alert(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('删除问题失败:', error);
            alert('删除问题失败，请稍后重试');
        });
    }
}

// 生成分页控件
function generatePagination(total, pageSize, currentPage) {
    const totalPages = Math.ceil(total / pageSize);
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = '<div class="pagination">';
    
    // 上一页
    if (currentPage > 1) {
        html += `<button class="page-btn" onclick="loadQuestions(${currentPage - 1})">上一页</button>`;
    } else {
        html += '<button class="page-btn disabled">上一页</button>';
    }
    
    // 页码
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, startPage + 4);
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentPage) {
            html += `<button class="page-btn active" onclick="loadQuestions(${i})"><strong>${i}</strong></button>`;
        } else {
            html += `<button class="page-btn" onclick="loadQuestions(${i})">${i}</button>`;
        }
    }
    
    // 下一页
    if (currentPage < totalPages) {
        html += `<button class="page-btn" onclick="loadQuestions(${currentPage + 1})">下一页</button>`;
    } else {
        html += '<button class="page-btn disabled">下一页</button>';
    }
    
    html += '</div>';
    pagination.innerHTML = html;
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 获取问题状态文本
function getStatusText(status) {
    switch (status) {
        case 0:
            return '待解决';
        case 1:
            return '已解决';
        case 2:
            return '已关闭';
        default:
            return '未知';
    }
}